# -*- coding=utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import tornado.template as te
import codecs
import sqlite3
import db
import markdown
version = "1.1"
version_info = (1, 1)
class html(object):
    def __init__(self):
        self.NEW = db.db("SELECT TITLE,SHORT,ID,tags,CREATETIME FROM MY WHERE LEIBIE<>'' ORDER BY CREATETIME DESC LIMIT 10") #最新10篇文章
        self.LEIBIE = db.db("SELECT LEIBIE FROM MY WHERE LEIBIE<>'' GROUP BY LEIBIE")	#取类别
        self.HASH = db.db("SELECT HASH FROM MY WHERE LEIBIE<>'' GROUP BY HASH")	#取日期归档
        self.LINK = db.db("SELECT ID,NAME,LINK FROM LINK WHERE TYPE='link'")		#取友情链接
        self.nav = db.db("SELECT ID,NAME,LINK FROM LINK WHERE TYPE='nav'")		#取导航链接
        self.Other = db.db("SELECT HTML FROM Other WHERE TYPE='belong' and LOCATION='last'")	#取文章附加內容
        self.conf = db.db("SELECT SITENAME,subtitle,description,keywords FROM CONFIG")          #取站點信息設定
        self.DUOSHUO = db.db("SELECT DUOSHUO FROM Ver")[0][0]
        self.JSCODE = db.db("SELECT HTML FROM Other WHERE NAME='JSCODE'")[0][0]
        self.NAME = self.conf[0][0]
        self.Subtitle = self.conf[0][1]
        self.description = self.conf[0][2]
        self.keywords = self.conf[0][3]
        self.dict = {}
        self.dict['HASH']=[i[0] for i in self.HASH]
        self.dict['LEIBIE']=[i[0] for i in self.LEIBIE]
        self.dict['NAME'] = self.NAME
        self.dict['Subtitle'] = self.Subtitle
        self.dict['description'] = self.description
        self.dict['tags'] = self.keywords
        self.dict['link'] = [(i[1],i[2]) for i in self.LINK]
        self.dict['nav'] = [(i[1],i[2]) for i in self.nav]
        self.dict['LIST'] = [(i[0],i[2]) for i in self.NEW]
        self.dict['TIME'] = ''
        self.dict['ID'] = '0'
        self.dict['title'] = self.NAME
        
    def Article(self):     #文章生成html文件
        LIST = db.db("SELECT TITLE,HTML,ID,tags,CREATETIME FROM MY ")
        for i in LIST:
            message = u'''<div class="ds-thread" data-thread-key="%s" data-title="%s" data-url="%s.html"></div>
		<script type="text/javascript"> var duoshuoQuery = {short_name:"%s"}; (function() { var ds = document.createElement('script'); ds.type = 'text/javascript';ds.async = true; ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js'; ds.charset = 'UTF-8'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ds); })(); </script> 
		</div> ''' % (i[2],i[0],i[2],self.DUOSHUO)
            body = self.BODY(i[2],i[0],i[3],i[4],i[1])
            self.dict['title']=i[0]
            self.dict['body']=body + self.tail() + message
            self.dict['ID']=i[2]
            self.dict['tags']=i[3]
            self.dict['TIME']=i[4]
            htmlurl = './html/%s.html' % i[2]
            self.tohtml(htmlurl)
            self.dict['title'] = self.NAME
            self.dict['tags']=self.keywords

    def BODY(self,ID,TITLE,tags,CREATE,HTML):  #組合HTML
        TXT = u'''<a href='%s.html' ><H1>%s</H1></a>
                <br><b>tags：%s   创建时间：%s</b><br><HR />
                %s <BR><HR />''' % (ID,TITLE,tags,CREATE,HTML)
        return TXT
    
    def tail(self):     #文章末尾追加
        TXTHTML = u''
        for i in self.Other:
            TXTHTML = TXTHTML + i[0]
        return TXTHTML
    def arch(self,TYPE,archive):     #归档HTML生成
        for i in archive:
            TXTHTML = u''
            s = db.db("SELECT TITLE,SHORT,ID,tags,CREATETIME FROM MY WHERE %s='%s' AND TYPE IS NULL ORDER BY CREATETIME DESC" % (TYPE,i))
            for t in s:
                TXTHTML = TXTHTML + self.BODY(t[2],t[0],t[3],t[4],t[1])
            self.dict['body'] = TXTHTML
            htmlurl = './html/%s.html' % i
            self.tohtml(htmlurl)
            
        
    def index(self):    #首页
        TXTHTML = u''
        for i in self.NEW:
            TXTHTML = TXTHTML + self.BODY(i[2],i[0],i[3],i[4],i[1])
        self.dict['body'] = TXTHTML
        htmlurl = './html/index.html'
        self.tohtml(htmlurl)
            
    def tohtml(self,htmlurl):   #HTML生成
        t = te.Template(codecs.open('./templates/main.html','r','utf-8').read())
        html = t.generate(title=self.dict['title'],body= self.dict['body'].replace('\'\'','\'').replace('\\\\','\\'),
                          tags= self.dict['tags'],TIME= self.dict['TIME'],
                          LIST= self.dict['LIST'],HASH= self.dict['HASH'],
                          LEIBIE=self.dict['LEIBIE'],Subtitle =  self.dict['Subtitle'],
                          NAME= self.dict['NAME'],ID= self.dict['ID'],description= self.dict['description'],
                          link= self.dict['link'],nav= self.dict['nav'],htmlurl=htmlurl,JSCODE = self.JSCODE)
        write = codecs.open(htmlurl,'wb','utf-8')
        write.write(html.encode('utf-8'))
        write.close()
    def ALL(self):
        self.Article()
        self.index()
        self.arch('LEIBIE',self.dict['LEIBIE'])
        self.arch('HASH',self.dict['HASH'])
if __name__=="__main__":
    html().ALL()
